<script setup>
import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance,
  computed,
  nextTick,
} from "vue";
import { useRouter } from "vue-router";

import * as echarts from "echarts";
import carbonEmission from "@/assets/mock/carbonEmission.json";

import api from "@/api";

const route = useRouter();
const { proxy } = getCurrentInstance();

const echartColors = [
  { c1: "#7AE6CE", c2: "#30C77E" },
  { c1: "#83BDFF", c2: "#6597FE" },
  { c1: "#F8C747", c2: "#F6AA17" },
];

//建筑全寿命周期碳排放总构成图-图表展示

const pieCount = ref([
  {
    name: "建造与拆除阶段",
    value: 8142.63,
  },
  {
    name: "运行阶段",
    value: 0,
  },
  {
    name: "生产与运输阶段",
    value: 79112.38,
  },
]);
let echartLobj = null;
const setEchartl = function () {
  let chartDom = document.getElementById("echart-l");
  let total = 0;
  pieCount.value.forEach((item) => {
    total += Number(item.value);
  });
  echarts.dispose(chartDom);
  echartLobj = echarts.init(chartDom);
  echartLobj.clear();
  let option = {
    title: {
      show: true,
      text: total.toFixed(2),
      subtext: "总计", //副标题文本，'\n'指定换行
      left: "center",
      top: "40%",
      zlevel: 9,
      textStyle: {
        fontSize: 25,
        align: "center",
        fontWeight: 700,
        color: "#F79810",
        fontFamily: "SourceHanSansSC",
      },
      subtextStyle: {
        fontSize: 23,
        align: "center",
        fontWeight: 600,
        fontFamily: "SourceHanSansSC",
        color: "#656565",
        lineHeight: 40,
      },
    },
    tooltip: {
      // trigger: "item",
    },
    series: [
      {
        type: "pie",
        radius: ["45%", "60%"],
        center: ["50%", "50%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 9,
          borderColor: "#fff",
          borderWidth: 0,
          color: function (params) {
            return new echarts.graphic.LinearGradient(1, 0, 0, 0, [
              {
                //颜色渐变函数 前四个参数分别表示四个位置依次为左、下、右、上

                offset: 0,
                color: echartColors[params.dataIndex].c1,
              },
              {
                offset: 1,
                color: echartColors[params.dataIndex].c2,
              },
            ]);
          },
        },
        label: {
          show: true,
          position: "outside",
          fontFamily: "SourceHanSansSC",
          formatter: function (params) {
            if (params.name !== "") {
              return `{${params.dataIndex}|${params.name} \n${params.percent}%}`;
            } else {
              return "";
            }
          },
          rich: {
            0: {
              color: echartColors[0].c1,
              fontWeight: "bold",
            },
            1: {
              color: echartColors[1].c1,
              fontWeight: "bold",
            },
            2: {
              color: echartColors[2].c1,
              fontWeight: "bold",
            },
          },
        },
        labelLine: {
          length: 15,
          length2: 0,
          show: true,
        },
        data: pieCount.value,
      },
    ],
  };
  option && echartLobj.setOption(option);
};

//单位面积碳排强度-图表展示
const xDataArea = ref(["生产与运输阶段", "建造与拆除阶段"]);
const yDataArea = ref([545.6, 56.16]);
let echartAreaObj = null;
const setEchartArea = function () {
  let chartDom = document.getElementById("echart-lm");
  let total = 0;
  pieCount.value.forEach((item) => {
    total += Number(item.value);
  });
  echarts.dispose(chartDom);
  echartAreaObj = echarts.init(chartDom);
  echartAreaObj.clear();
  let option = {
    grid: {
      top: 50,
      bottom: 35,
    },
    label: {
      show: true,
      position: "top",
      color: "#FFD59A",
      fontSize: 14,
      fontWeight: 700,
    },
    tooltip: {
      // trigger: "item",
    },
    legend: {
      data: ["单位面积碳排放强度 kgCO₂e/㎡"],
      align: "left",
      top: 10,
      textStyle: {
        fontFamily: "SourceHanSansSC",
        color: "#656565",
      },
      itemWidth: 20,
      itemHeight: 10,
    },
    xAxis: {
      data: xDataArea.value,
      axisLabel: {
        fontFamily: "SourceHanSansSC",
        color: "#656565",
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: true, //不显示坐标轴线
        lineStyle: {
          color: "#939393 ",
        },
      },
      z: 10,
    },
    yAxis: {
      axisLine: {
        show: true, //不显示坐标轴线
        lineStyle: {
          color: "#939393 ",
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        fontFamily: "SourceHanSansSC",
        color: "#656565",
      },
      splitLine: {
        //网格线
        show: true,

        lineStyle: {
          type: "dashed",
          color: "#8E8E8E",
        },
      },
    },
    series: [
      {
        name: "单位面积碳排放强度 kgCO₂e/㎡",
        type: "bar",
        barWidth: 40,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#FFD59A" },
            { offset: 1, color: "#FECF73" },
          ]),
        },
        data: yDataArea.value,
      },
    ],
  };
  option && echartAreaObj.setOption(option);
};

//平均每年碳排放强度-图表展示
const xDataYear = ref(["生产与运输阶段", "建造与拆除阶段"]);
const yDataYear = ref([1582247.6, 162852.6]);
let echartYearObj = null;
const setEchartYear = function () {
  let chartDom = document.getElementById("echart-rm");
  let total = 0;
  pieCount.value.forEach((item) => {
    total += Number(item.value);
  });
  echarts.dispose(chartDom);
  echartYearObj = echarts.init(chartDom);
  echartYearObj.clear();
  let option = {
    grid: {
      top: 50,
      bottom: 35,
    },
    legend: {
      data: ["平均每年碳排放强度 kgCO₂e/㎡"],
      align: "left",
      top: 10,
      textStyle: {
        fontFamily: "SourceHanSansSC",
        color: "#656565",
      },
      itemWidth: 20,
      itemHeight: 10,
    },
    label: {
      show: true,
      position: "top",
      color: "#9AC6FF",
      fontSize: 14,
      fontWeight: 700,
    },
    tooltip: {
      // trigger: "item",
    },
    xAxis: {
      data: xDataYear.value,
      axisLabel: {
        fontFamily: "SourceHanSansSC",
        color: "#656565",
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: true, //不显示坐标轴线
        lineStyle: {
          color: "#939393 ",
        },
      },
      z: 10,
    },
    yAxis: {
      name:'（万）',
      nameTextStyle: {
        padding: [0, 0, 0, -10],
        fontFamily: "SourceHanSansSC",
      },
      axisLine: {
        show: true, //不显示坐标轴线
        lineStyle: {
          color: "#939393 ",
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        fontFamily: "SourceHanSansSC",
        color: "#656565",
        formatter: function (value, index) {
          if (value >= 10000) {
            return value / 10000;
          }
        },
      },
      splitLine: {
        //网格线
        show: true,

        lineStyle: {
          type: "dashed",
          color: "#8E8E8E",
        },
      },
    },
    series: [
      {
        name: "平均每年碳排放强度 kgCO₂e/㎡",
        type: "bar",
        barWidth: 40,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#9AC6FF" },
            { offset: 1, color: "#73AAFE" },
          ]),
        },
        data: yDataYear.value,
      },
    ],
  };
  option && echartYearObj.setOption(option);
};

//平均每年单位面积碳排放强度-图表展示
const xDataYearArea = ref(["生产与运输阶段", "建造与拆除阶段"]);
const yDataYearArea = ref([10.91, 1.12]);
let echartYearAreaObj = null;
const setEchartYearArea = function () {
  let chartDom = document.getElementById("echart-r");
  let total = 0;
  pieCount.value.forEach((item) => {
    total += Number(item.value);
  });
  echarts.dispose(chartDom);
  echartYearAreaObj = echarts.init(chartDom);
  echartYearAreaObj.clear();
  let option = {
    grid: {
      top: 50,
      bottom: 35,
    },
    legend: {
      data: ["平均每年单位面积碳排放强度 kgCO₂e/㎡"],
      align: "left",
      top: 10,
      textStyle: {
        fontFamily: "SourceHanSansSC",
        color: "#656565",
      },
      itemWidth: 20,
      itemHeight: 10,
    },
    label: {
      show: true,
      position: "top",
      color: "#4CE381",
      fontSize: 14,
      fontWeight: 700,
    },
    tooltip: {
      // trigger: "item",
    },
    xAxis: {
      data: xDataYearArea.value,
      axisLabel: {
        fontFamily: "SourceHanSansSC",
        color: "#656565",
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: true, //不显示坐标轴线
        lineStyle: {
          color: "#939393 ",
        },
      },
      z: 10,
    },
    yAxis: {
      nameTextStyle: {
        padding: [0, 0, 0, -10],
        fontFamily: "SourceHanSansSC",
      },
      axisLine: {
        show: true, //不显示坐标轴线
        lineStyle: {
          color: "#939393 ",
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        fontFamily: "SourceHanSansSC",
        color: "#656565",
      },
      splitLine: {
        //网格线
        show: true,

        lineStyle: {
          type: "dashed",
          color: "#8E8E8E",
        },
      },
    },
    series: [
      {
        name: "平均每年单位面积碳排放强度 kgCO₂e/㎡",
        type: "bar",
        barWidth: 40,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#4CE381" },
            { offset: 1, color: "#5EF080" },
          ]),
        },
        data: yDataYearArea.value,
      },
    ],
  };
  option && echartYearAreaObj.setOption(option);
};

onMounted(() => {
  setEchartl();
  setEchartArea();
  setEchartYear();
  setEchartYearArea();
  window.onresize = _.debounce(() => {
    echartLobj && echartLobj.resize();
    echartAreaObj && echartAreaObj.resize();
    echartYearObj && echartYearObj.resize();
    echartYearAreaObj && echartYearAreaObj.resize();
  }, 300);
});

/**
 * 设置el-table中合计行合并单元格
 * @param {*} cls 表格类名
 * @param {*} num 合并的单元格数量
 */
const mergeCell = function (cls, num) {
  nextTick(() => {
    setTimeout(() => {
      const tds = document.querySelectorAll(cls);

      tds[0].colSpan = num;
      tds[0].style.textAlign = "center";
      for (let i = 0; i < num; i++) {
        if (i === 0) continue;
        tds[i].style.display = "none";
      }
    });
  }, 50);
};

//建筑全寿命周期碳排放量汇总
const tableDataLeft = ref([]);
tableDataLeft.value = carbonEmission.Summary.value;

const getSummariesLeft = function (param) {
  // const { columns, data } = param
  // let sums = [];
  // columns.forEach((column, index) => {
  //   if (index === 0) {
  //     sums[index] = '总计'
  //     return
  //   }
  //   const values = data.map((item) => {
  //     //阶段合计的数据不计入总数里
  //     if (item.sources === '阶段合计') {
  //       return 0
  //     } else {
  //       return Number(item[column.property])
  //     }
  //   })
  //   if (!values.every((value) => Number.isNaN(value))) {
  //     sums[index] = Number(`${values.reduce((prev, curr) => {
  //       const value = Number(curr)
  //       if (!Number.isNaN(value)) {
  //         return prev + curr
  //       } else {
  //         return prev
  //       }
  //     }, 0)}`).toFixed(2)
  //   } else {
  //     sums[index] = 'N/A'
  //   }
  // });
  return carbonEmission.Summary.total;
};

const spanMethodLeft = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 0) {
    if (rowIndex < 3) {
      if (rowIndex == 0) {
        return {
          rowspan: 3,
          colspan: 1,
        };
      } else {
        return {
          rowspan: 0,
          colspan: 0,
        };
      }
    }

    if (rowIndex < 6) {
      if (rowIndex == 3) {
        return {
          rowspan: 3,
          colspan: 1,
        };
      } else {
        return {
          rowspan: 0,
          colspan: 0,
        };
      }
    }

    if (rowIndex < 15) {
      if (rowIndex == 6) {
        return {
          rowspan: 9,
          colspan: 1,
        };
      } else {
        return {
          rowspan: 0,
          colspan: 0,
        };
      }
    }
    if (rowIndex == 15) {
      return {
        rowspan: 1,
        colspan: 2,
      };
    }
  }
};
mergeCell(".table-l .el-table__footer-wrapper tr>td", 2);

//用水量
const tabs = ref([
  {
    label: "建材生产碳排放",
    value: "produce",
  },
  {
    label: "建造阶段碳排放",
    value: "construct",
  },
  {
    label: "运行阶段碳排放",
    value: "run",
  },
  {
    label: "拆除阶段碳排放",
    value: "remove",
  },
]);

//右侧默认展示第一个
const activeIndex = ref(0);
const tableDataRight = ref({});
tableDataRight.value = carbonEmission.produce;
mergeCell(".table-r .el-table__footer-wrapper tr>td", 5);

const operatePhase = ref({});

//数据原因，总计写死
const getSummariesRight = function () {
  return tableDataRight.value.total;
};

//tabs切换
const tabHandleClick = function (item, index) {
  if (activeIndex.value === index) return;
  activeIndex.value = index;
  if (activeIndex.value === 2) {
    operatePhase.value = carbonEmission[item.value];
    mergeCell(".operatePhase .el-table__footer-wrapper tr>td", 2);
    mergeCell(".operatePhase .el-table__header tr>th", 2);
  } else {
    tableDataRight.value = carbonEmission[item.value];
    mergeCell(".table-r .el-table__footer-wrapper tr>td", 5);
  }
};

//运行阶段碳排放处理
const spanMethodOp = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 0) {
    if (rowIndex < 4) {
      if (rowIndex == 0) {
        return {
          rowspan: 4,
          colspan: 1,
        };
      } else {
        return {
          rowspan: 0,
          colspan: 0,
        };
      }
    }

    if (rowIndex < 7) {
      if (rowIndex == 4) {
        return {
          rowspan: 3,
          colspan: 1,
        };
      } else {
        return {
          rowspan: 0,
          colspan: 0,
        };
      }
    }

    if (rowIndex < 10) {
      if (rowIndex == 7) {
        return {
          rowspan: 3,
          colspan: 1,
        };
      } else {
        return {
          rowspan: 0,
          colspan: 0,
        };
      }
    }
    if (rowIndex < 13) {
      if (rowIndex == 10) {
        return {
          rowspan: 3,
          colspan: 1,
        };
      } else {
        return {
          rowspan: 0,
          colspan: 0,
        };
      }
    }
  }
};

const getSummariesOp = function () {
  return operatePhase.value.total;
};
</script>

<template>
  <div class="container">
    <div class="echarts-box">
      <div class="gridcell">
        <div class="title">建筑全寿命周期碳排放总构成图</div>
        <div class="echart" id="echart-l"></div>
      </div>
      <div class="gridcell">
        <div class="title">单位面积碳排强度</div>
        <div class="echart" id="echart-lm"></div>
      </div>
      <div class="gridcell">
        <div class="title">平均每年碳排放强度</div>
        <div class="echart" id="echart-rm"></div>
      </div>
      <div class="gridcell">
        <div class="title">平均每年单位面积碳排放强度</div>
        <div class="echart" id="echart-r"></div>
      </div>
    </div>
    <div class="table-box">
      <div class="gridcell">
        <div class="title">建筑全寿命周期碳排放量汇总</div>
        <el-table
          class="table-l"
          :data="tableDataLeft"
          :span-method="spanMethodLeft"
          show-summary
          :summary-method="getSummariesLeft"
          sum-text="总计"
          border
          style="width: 100%"
          height="calc(100vh - 475px)"
        >
          <el-table-column
            align="center"
            prop="activityPhase"
            label="活动阶段"
            width="100"
          />
          <el-table-column align="center" prop="sources" label="碳排放来源">
          </el-table-column>
          <el-table-column align="center" prop="total" label="">
            <template #header>
              <span>总碳排放量<br />
                tCO₂e</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="average" label="">
            <template #header>
              <span>平均碳排放量<br />
                kgCO₂e/a</span>
            </template></el-table-column>
          <el-table-column align="center" prop="intensity" label="">
            <template #header>
              <span
                >碳排放强度<br />
                kgCO₂e/(m²·a)</span
              >
            </template>
          </el-table-column>
          <el-table-column align="center" prop="percent" label="">
            <template #header>
              <span>碳排量占比<br />
                %</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="gridcell">
        <div class="tabs">
          <div
            class="tab-item"
            :class="activeIndex === index ? 'active' : ''"
            v-for="(item, index) in tabs"
            :key="index"
            @click="tabHandleClick(item, index)"
          >
            <span>{{ item.label }}</span>
          </div>
        </div>
        <div v-if="activeIndex !== 2">
          <el-table
            class="table-r"
            :data="tableDataRight.value"
            show-summary
            :summary-method="getSummariesRight"
            sum-text="总计"
            border
            style="width: 100%"
            height="calc(100vh - 570px)"
          >
            <el-table-column
              align="center"
              prop="name"
              label="名称"
              width="180"
            />
            <el-table-column align="center" prop="specifications" label="规格">
            </el-table-column>
            <el-table-column align="center" prop="unit" label="单位" />
            <el-table-column align="center" prop="num" label="数量" />
            <el-table-column align="center" prop="factor" width="150" label="">
              <template #header>
                <span
                  >碳排放因子<br />
                  kgCO₂e/(单位数量)</span
                >
              </template>
            </el-table-column>
            <el-table-column align="center" prop="emissions" label="">
              <template #header>
                <span
                  >碳排放量<br />
                  tCO₂e</span
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="info">
            {{ tableDataRight.desc }}
          </div>
        </div>
        <div v-else>
          <el-table
            class="operatePhase"
            :data="operatePhase.value"
            :span-method="spanMethodOp"
            show-summary
            :summary-method="getSummariesOp"
            sum-text="总计"
            border
            style="width: 100%"
            height="calc(100vh - 570px)"
          >
            <el-table-column
              align="center"
              prop="largeCategory"
              label="分项"
              width="180"
            />
            <el-table-column align="center" prop="subclass" label="">
            </el-table-column>
            <el-table-column align="center" prop="emissions" label="">
              <template #header>
                <span
                  >碳排放量<br />
                  tCO2e</span
                >
              </template>
            </el-table-column>
            <el-table-column align="center" prop="intensity" label="">
              <template #header>
                <span
                  >碳排放强度<br />
                  kgCO2e/(m2·a)</span
                >
              </template>
            </el-table-column>
            <el-table-column align="center" prop="average" label="">
              <template #header>
                <span
                  >年均碳排放量<br />
                  kgCO2e/a</span
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="info">
            {{ operatePhase.desc }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: calc(100vh - 79px);
  font-family: SourceHanSansSC;
  display: flex;
  color: #656565;
  flex-direction: column;
  overflow: auto;

  .echarts-box {
    width: 100%;

    .gridcell {
      width: calc(25% - 10px);
      height: 320px;
      float: left;
      margin: 5px;
      border: 1px solid #dce3ef;
      box-shadow: 2px 2px 0px 0px rgba(236, 238, 252, 0.32);
      border-radius: 6px;
      padding: 15px 5px;
      box-sizing: border-box;

      .title {
        height: 20px;
        padding-left: 5px;
        font-size: 16px;
        margin-left: 10px;
        font-weight: 600;
        color: #656565;
        line-height: 20px;
        border-left: 3px solid #8f93f7;
      }

      .echart {
        width: 100%;
        height: 280px;
      }
    }

    @media screen and (max-width: 1600px) {
      .gridcell {
        width: calc(50% - 10px);
      }
    }
  }

  .table-box {
    width: 100%;

    .gridcell {
      width: calc(50% - 10px);
      height: calc(100vh - 420px);
      min-height: 500px;
      float: left;
      margin: 5px;
      border: 1px solid #dce3ef;
      box-shadow: 2px 2px 0px 0px rgba(236, 238, 252, 0.32);
      border-radius: 6px;
      padding: 15px 5px;
      box-sizing: border-box;

      .title {
        height: 20px;
        padding-left: 5px;
        font-size: 16px;
        margin: 0px 0px 10px 10px;
        font-weight: 600;
        color: #656565;
        line-height: 20px;
        border-left: 3px solid #8f93f7;
      }

      :deep .el-table {
        .el-table__footer-wrapper tbody td.el-table__cell {
          background-color: unset;
        }

        th.el-table__cell {
          background-color: #ecedff;
        }

        .el-table__cell {
          padding: 4px 0px;
        }
      }

      .tabs {
        width: 100%;
        height: 50px;
        box-sizing: border-box;
        display: flex;
        justify-content: space-around;
        margin-top: 10px;

        .tab-item {
          width: 190px;
          height: 30px;
          border: 1px solid #cbcbcb;
          border-radius: 4px;
          text-align: center;
          line-height: 30px;
          font-size: 13px;
          color: #656565;
          cursor: pointer;

          &.active {
            border: 1px solid #6e91fb;
            color: #6e91fb;
            font-weight: bold;
          }
        }
      }

      .info {
        width: 100%;
        height: 40px;
        line-height: 40px;
        text-align: center;
        background: rgba(229, 229, 229, 0.2);
      }
    }

    .gridcell:nth-child(1) {
      :deep .el-table {
        min-height: 440px;

        .el-table__inner-wrapper {
          min-height: 440px;

          tbody td.el-table__cell {
            background-color: unset;
          }
        }
      }
    }

    .gridcell:nth-child(2) {
      :deep .el-table {
        min-height: 385px;

        .el-table__inner-wrapper {
          min-height: 385px;

          tbody td.el-table__cell {
            background-color: unset;
          }
        }
      }
    }
  }
}
</style>
